<template>
	<view>
		<view style="width:100vw; min-height: 526.5rpx; background: #000000; display: flex; justify-content: center; align-items:center;">
			<image v-if="!currentVideo.url" src="https://statics.xmcsrv.net/weixin/noVideo.png" style="width: 120rpx;height: 120rpx;"></image>
			<video 
				v-if="currentVideo.url"
				id="video" 
				style="width: 100%" 
				:src="currentVideo.url" 
				autoplay 
				@ended="ended"
				@loadedmetadata="bindloadedmetadata"
				@play="bindplay"
				@fullscreenchange="handleFullscreenChange"
			></video>
		</view>

		<scroll-view :scroll-x="true" class="video-list">
			<template v-if="playBackUrlList.length > 0">
				<view class="video" v-for="(item,index) in playBackUrlList" :key="index">
					<view class="video-control">
						<view style="position: absolute; top: 10rpx; font-size: 18rpx; text-align: center;">{{item.BeginTime}}</view>
						<uni-icons 
							custom-prefix="iconfont" 
							type="icon-bofang1" 
							size="36" 
							color="#999999"
							v-if="item.status !== 1" 
							@click="onPlay(item)"
						></uni-icons>
						<view v-else>
						<uni-icons 
							custom-prefix="iconfont" 
							type="icon-zanting2" 
							size="36" 
							color="#999999" 
							@click="onPause(item)"
						></uni-icons>
						<uni-icons
							custom-prefix="iconfont" 
							type="icon-tingzhi4" 
							size="36" 
							color="#999999" 
							@click="onStop(item)"
						></uni-icons>
						</view>
						<view style="position: absolute; bottom: 10rpx; font-size: 18rpx; text-align: center;">{{item.EndTime}}</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="video-nothing">
					<view>
						<uni-icons custom-prefix="iconfont" type="icon-kong" size="64"></uni-icons>
						<view>无录像</view>
					</view>
				</view>
			</template>
		</scroll-view>

		<view style="padding:0 20rpx;">
			<uni-datetime-picker type="date" :clear-icon="false" v-model="single" @change="change"
				@maskClick="maskClick" />
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				ifOnce:0,
				device: '',
				videoContext:null,
				playBackUrlList: [],
				currentVideo:{
					key:'',
					url:''
				},
				fullscreen:false,
				single: '',
				isLoading:true,
			}
		},
		onLoad: function(options) {
			// console.log(JSON.parse(options.device));
			let enData = decodeURIComponent(options.device)
			this.device = JSON.parse(enData);
			this.single = new Date().toJSON().split('T')[0]
			this.getPlayBackUrlList()
		},
		onShow(){
			this.$postPointData({code:'600918', eventName:'into_page_card_play_back'})
		},
		methods: {
			// 获取回放列表
			getPlayBackUrlList() {
				uni.showLoading()
				const token = this.device.token;
				const data = {
					Name: 'OPFileQuery',
					OPFileQuery: {
						BeginTime: this.single + ' 00:00:00',
						EndTime: this.single + ' 23:59:59',
						Channel: 0,
						DriverTypeMask: '0x0000FFFF',
						Event: '*',
						StreamType: '0x00000000',
						Type: 'h264'
					}
				};
				getApp().globalData.api.opdev(data, token, (result) => {
					console.log('获取回放列表:', result);
					uni.hideLoading()
					this.playBackUrlList = result.OPFileQuery || []
					if (this.playBackUrlList.length > 0) {
						this.playBackUrlList.forEach((item,index) => {
							// 播放状态：播放1，暂停0，停止-1
							this.$set(item,'status',-1)
							this.$set(item,'key',index)
						})
						this.playbackUrl(this.playBackUrlList[0], result => {
							this.keepRequestUntillRight(result)
						})
					}
				});
			},
			// 获取设备回放地址
			playbackUrl(item, callback) {
				uni.showLoading()
				const token = this.device.token;
				const data = {
					channel: 0,
					streamType: 0,
					startTime: item.BeginTime,
					endTime: item.EndTime,
					username: this.device.devUserName,
					devPwd: this.device.devPassWord,
					fileName: item.FileName,
					userToken: uni.getStorageSync('accessToken'),
					appKey:getApp().globalData.api.appKey,
					encryptType: 'DISABLE',
				};
				if(this.device.adminToken){
					data.authentication = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				getApp().globalData.api.playbackUrl(data, token, (result) => {
					// console.log('获取设备回放地址:', result);
					// uni.hideLoading()
					// 播放地址
					this.$set(item, 'url', result.url)
					// 回调
					if(typeof callback === 'function'){
						callback(item)
					}
				});
			},
			// 一直请求直到请求成功（处理：渲染层网络层错误）
			keepRequestUntillRight(item) {
				uni.showLoading()
				console.log('=====一直请求直到请求成功=======');
				uni.request({
					method: 'GET',
					url:item.url,
					success: (res) => {
						if (res.statusCode == 200) {
							this.ifOnce+=1;
							this.currentVideo = {
								key:item.key,
								url:item.url
							}
							item.status = 1
							this.videoContext  = uni.createVideoContext('video')

						} else if (res.statusCode == 400) {
							uni.showModal({
								title: '提示',
								content: res.data,
								showCancel: false
							});
						} else {
							setTimeout(() => {
								this.keepRequestUntillRight(item);
							}, 1000);
						}
					},
					fail: (err) => {
						console.log('error:', err);
					}
				});
			},
			// 点击播放
			onPlay(item) {
				if(this.isLoading){
					return
				}
				console.log('点击播放：',item,this.currentVideo,this.isLoading);
				// 判断item是不是当前正在播放的currentVideo
				if(item.key === this.currentVideo.key){
					if(this.currentVideo.url !== '' && this.currentVideo.key === ''){
						this.videoContext  = uni.createVideoContext('video')
					}
					//停止时，去播放
					if(item.status === -1){
						this.playbackUrl(item, result => {
							this.keepRequestUntillRight(result)
						})
					}
					// 暂停时，去播放
					else if(item.status === 0){
						this.videoContext.play()
						item.status = 1
					}
				}else{
					this.isLoading = true
					this.onStop()
					this.playbackUrl(item, result => {
						this.keepRequestUntillRight(result)
					})
				}
			},
			// 暂停
			onPause(item){
				if(this.isLoading){
					return
				}
				this.videoContext.pause()
				item.status = 0
			},
			onStop(){
				if(this.videoContext){
					this.videoContext.stop()
					this.closeLivestream()
					this.videoContext = null
				}
				this.currentVideo = {
					url:'',
					key:''
				}
				this.playBackUrlList.forEach(item=>{
					item.status = -1
				})
			},
			bindplay(e){
				uni.hideLoading()
				this.isLoading = false
				console.log('播放开始：',e,this.currentVideo);
				this.$postPointData({code:'600906',eventName:'click_card_play_back_play',screen_orientation:this.fullscreen})
				if(this.ifOnce==1){
					this.$postPointData({code:'600919', eventName:'page_card_play_back_success'})
				}
			},	
			ended(ev){
				console.log('播放结束：',ev,this.currentVideo);
				let current = this.playBackUrlList[this.currentVideo.key]
				current.status = -1
				if(this.videoContext){
					this.closeLivestream()
					this.videoContext = null
				}
				
				let key = this.currentVideo.key + 1
				let item = this.playBackUrlList[key]
				this.playbackUrl(item, result => {
					this.keepRequestUntillRight(result)
				})
			},
			// 视频元数据加载完成时触发
			bindloadedmetadata(e){
				console.log('视频元数据加载完成时触发',e);
			},
			handleFullscreenChange(e){
				this.fullscreen = e.detail.fullScreen
        if (e.detail.fullScreen) {
          console.log("视频进入全屏模式");
        } else {
          console.log("视频退出全屏模式");
        }
				this.$postPointData({code:'600904',eventName:'click_card_play_back_screen_orientation',isFullScreen:e.detail.fullScreen})
			},
			// 停止设备码流
			closeLivestream(callback) {
				const token = this.device.token;
				const data = {
					channel: '0',
					stream: '0',
					PassWord:this.device.devPassWord,
					UserName:this.device.devUserName,
					EncryptType:'DISABLE',
					Authentication:this.device.token
				};
				getApp().globalData.api.closeLivestream(data, token, (result) => {
					console.log('停止设备码流:', result);
				});
			},
			change(ev) {
				console.log('change事件:', ev);
				this.$postPointData({code:'600902', eventName:'click_card_play_back_calender'})
				this.single = ev
				this.onStop()
				this.getPlayBackUrlList()
			},
			maskClick(ev) {
				console.log('maskClick事件:', ev);
			}
		}
	}
</script>

<style>
	.video-list {
		width: 100vw;
		height: 40vw;
		white-space: nowrap;
	}

	.video {
		display: inline-block;
		width: 30vw;
		height: 30vw;
		overflow: hidden;
		border: 1px solid #999999;
		margin: 20rpx;
	}

	.video-control {
		position: relative;
		display: flex;
		width: 100%;
		height: 100%;
		justify-content: center;
		align-items: center;
	}

	.video-nothing {
		display: flex;
		width: 100%;
		height: 100%;
		justify-content: center;
		align-items: center;
	}
</style>
